with open('score_sheet.txt') as f:
    lines = f.readlines()
    score_sheet_dict = {}
    for line in lines:
        if line == "\n":
            continue
        else:
            if line.strip()[0] != '#':
                line = line.replace(' ', '').replace('\t', '').replace('\n', '')
                line = list(line.split(','))
                score_sheet_dict[int(line[0])] = (line[1], int(line[2]))
    #print(score_sheet_dict)  #打印学生成绩组成的字典
    #(1)输出成绩平均数和中位数
    score_sum = 0
    score_list = []
    for record in score_sheet_dict.values():
        score_sum += record[1]
        score_list.append(record[1])
    count = len(score_sheet_dict) #学生个数
    score_list.sort()
    #print(score_list)
    print("该班级平均成绩为"+str(round(score_sum/len(score_sheet_dict), 2)))
    if count % 2 == 0:
        print("该班级成绩中位数为"+str((round(score_list[int(count/2)-1]+score_list[int(count/2)], 2)/2)))
    else:
        print("该班级成绩中位数为"+str(round(score_list[int(count/2)], 2)))
    #(2)按照学生ID（整数类型）的顺序输出成绩单
    print('ID'+' '*4+'Name'+' '*8+'Score')
    print('-------------------------')
    for ID in sorted(score_sheet_dict):
        name = score_sheet_dict[ID][0]
        score = score_sheet_dict[ID][1]
        print(str(ID)+' '*(6-len(str(ID)))+name+' '*(12-len(name))+str(score))
    #(3)按照成绩排序输出成绩单
    print('ID' + ' ' * 4 + 'Name' + ' ' * 8 + 'Score')
    print('-------------------------')
    for record in sorted(score_sheet_dict.items(), key=lambda x: (x[1][1], x[1][0])):
        ID = record[0]
        name = record[1][0]
        score = record[1][1]
        print(str(ID)+' '*(6-len(str(ID)))+name+' '*(12 -len(name))+str(score))
    #(4)统计每个分数对应了哪些同学，保存在一个字典中
    score_list = list(set(score_list))
    #print(score_list)
    score_ID_dict = {}
    for score in score_list:
        ID_list = []
        for record in score_sheet_dict.items():
            if score == record[1][1]:
                ID_list.append(record[0])
        score_ID_dict[score] = len(ID_list)
    #print(score_ID_dict)
    most_score_list = sorted(score_ID_dict.items(), key=lambda x: x[1], reverse=True)
    print("Score   Count")
    print('-----------------')
    for record in most_score_list[0:5]:
        print(str(record[0])+' '*6+str(record[1]))